package com.hspedu.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 通过反射机制创建实例
 */
public class ReflectionCreateInstance {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class<?> userClass = Class.forName("com.hspedu.reflection.User");

        //1、通过 public 无参构造器创建实例
        Object o = userClass.newInstance();
        System.out.println(o);
        //2、通过 public 有参构造器创建实例
        Constructor<?> constructor = userClass.getConstructor(String.class);
        Object o1 = constructor.newInstance("小红");
        System.out.println(o1);
        //3、通过非 public 有参构造器创建实例
        Constructor<?> declaredConstructor = userClass.getDeclaredConstructor(String.class, int.class);
        //爆破
        declaredConstructor.setAccessible(true);

        Object o2 = declaredConstructor.newInstance("小白", 24);
        System.out.println(o2);
    }
}

class User {
    private String name = "小明";
    private int age = 18;

    public User() {
    }

    public User(String name) {
        this.name = name;
    }

    private User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
